<template>
    <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage">
    
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
import Cos from 'cos-js-sdk-v5'
  export default {
    props: {
        value: {
            type: String,
            default: ''
        }
    },
    methods: {
      handleAvatarSuccess(res, file) {
       
      },
      beforeAvatarUpload(file) {

        const typeArr = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
        const isJPG = typeArr.includes(file.type)
        const isLt2M = file.size / 1024 / 1024 < 5;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 jpg/png/gif/bmp 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 5MB!');
        }
        return isJPG && isLt2M;
      },
      // 图片上传
      uploadImage(params) {
        // console.log(params.file);
        // 创建腾讯云sdk对象
        const cos = new Cos({
          SecretId: 'AKIDiGbzRm13qQmz3WncGiCefTBmFdwRtFci',
          SecretKey: 'DLQJzShleO4d0Snz1wifVErPq9c2KXaQ'
        }) // 完成cos初始化

        // 上传方法
        cos.putObject({
          Bucket: 'dtt-1323295954', /* 填入您自己的存储桶，必须字段 */
          Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
          Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
          StorageClass: 'STANDARD', // 固定字段
          Body: params.file, // 上传文件对象
        },(err, data) => {
          // 错误信息 / data返回数据
          // console.log(data);
          if (data.statusCode === 200 && data.Location) {
            this.$emit('input', 'http://' + data.Location)
          }
          else {
            this.$message.error('上传图片失败，请重试！')
          }
        })
      }
    }
  }
</script>